package com.hystrix.command;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCommand;

public class CollapserCommand extends HystrixCollapser<List<String>, String, Integer> {

	private final Integer key;

	public CollapserCommand(Integer key) {
		this.key = key;
	}

	@Override
	public Integer getRequestArgument() {
		return key;
	}

	@Override
	protected HystrixCommand<List<String>> createCommand(Collection<CollapsedRequest<String, Integer>> requests) {
		// 创建返回command对象
		List<String> ids = new ArrayList<>(requests.size());
		for (CollapsedRequest<String, Integer> request : requests) {
			ids.add(request.getArgument().toString());
		}
		return new CollapserBatchCommand(ids);
	}

	@Override
	protected void mapResponseToRequests(List<String> batchResponse,
			Collection<CollapsedRequest<String, Integer>> requests) {
		int count = 0;
		for (CollapsedRequest<String, Integer> collapsedRequest : requests) {
			String book = batchResponse.get(count++);
			collapsedRequest.setResponse(book);
		}
	}

}
